<template>
  <el-cascader v-model="selectList" :options="groupTree" style="width: 100%" :show-all-levels="false"
    :props="{ value: 'id', label: 'name', multiple: 'true', checkStrictly: false }" @change="groupChange"
    clearable></el-cascader>
</template>

<script>
  import {
    groupTree
  } from '@/api/user';
  export default {
    name: 'SelectGroup',
    props: {
      /* JSON字符串 */
      value: {
        type: String,
        default: null
      }
    },
    data() {
      return {
        groupTree: [],
        selectList: []
      };
    },
    watch: {
      value: {
        handler(val) {
          var list = [];
          try {
            list = val ? JSON.parse(val) : [];
          } catch (e) {
            console.log('JSON解析出错', val);
          }
          this.selectList = list.map((item) => {
            var list = item.groupPath.split('/');
            if (!list[list.length - 1]) list.pop();
            return list;
          });
        },
        immediate: true
      }
    },
    created() {
      this.getGroupTree();
    },
    methods: {
      // 获取部门树
      getGroupTree() {
        groupTree().then((res) => {
          this.groupTree = res.data || [];
        });
      },
      groupChange(e) {
        this.groupList = [];
        e.map((ids) => {
          this.getGroupItem(this.groupTree, JSON.parse(JSON.stringify(ids)));
          if (this.selectGroupItem) {
            this.groupList.push({
              groupId: this.selectGroupItem.id,
              groupPath: this.selectGroupItem.path,
              groupName: this.selectGroupItem.name
            });
            this.selectGroupItem = null;
          } else {
            console.log('递归树未找到值：', ids);
          }
        });

        this.$emit('input', this.groupList.length ? JSON.stringify(this.groupList) : '');
      },
      getGroupItem(tree, ids) {
        if (!tree || !tree.length) return null;
        if (!ids || !ids.length) return null;
        const id = ids.shift();
        const item = tree.find((i) => i.id == id);
        if (ids.length && item.children) {
          this.getGroupItem(item.children, ids);
        } else {
          this.selectGroupItem = item;
        }
      }
    }
  };
</script>

<style scoped lang="scss"></style>
